package com.bayihouse.excel.converter;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.enums.CellDataTypeEnum;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import com.bayihouse.excel.converter.AgeConverter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.stream.Collectors;

public class MyDateConverter implements Converter<Date> {
    public Class supportJavaTypeKey() {
        return Date.class;
    }

    public CellDataTypeEnum supportExcelTypeKey() {
        return CellDataTypeEnum.STRING;
    }

    public Date convertToJavaData(ReadCellData<?> cellData, ExcelContentProperty contentProperty,
                                  GlobalConfiguration globalConfiguration) throws ParseException {
        if (cellData.getStringValue() == null || cellData.getStringValue().equals("")) {
            return null;
        }
        String format = "yyyy-MM-dd";
        Map<String, String> dateMap = AgeConverter.dateMap;
        if (dateMap.keySet().stream().anyMatch(key -> cellData.getStringValue().matches(key))) {
            format = dateMap.get(dateMap.keySet().stream().filter(key -> cellData.getStringValue().matches(key)).collect(Collectors.toList()).get(0));
        }
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat(format);
        return simpleDateFormat.parse(cellData.getStringValue());
    }
}
